/**
 * 版权所有 2009-2015 中国中医科学院中医药信息研究所 何前锋 frontpeak@yahoo.com.cn
 **/
package cn.ac.cintcm.sh.domain;

import java.util.HashMap;
import java.util.Iterator;
import java.util.Set;

public class View {
    
    private int id;
    private String name;
    private HashMap<Herb, Rule> rules;
    
    public View(String name) {
        this.name = name;
        rules = new HashMap<Herb, Rule>();
    }
    
    public View() {
        rules = new HashMap<Herb, Rule>();
    }
    
    public static void main(String[] args) {
    }
    
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
    public HashMap<Herb, Rule> getRules() {
        return rules;
    }
    public void setRules(HashMap<Herb, Rule> rules) {
        this.rules = rules;
    }
    
    public Rule getRule(Herb herb) {
        return rules.get(herb);
    }
    /**
     * ���չ���ת��ҩ�����
     * @param herb
     * @return
     */
    public Unit calculate(Herb herb) {
        Unit unit = new Unit();
        if (herb != null) {
            Rule rule = getRule(herb);
            if (rule == null) {
            	rule = getRule(herb.createEmptyNameHerb());
            }
            if (rule != null) {
            	unit.setQuantity(
                    herb.getDosage().getQuantity() * rule.getUnit().getQuantity());
                unit.setUnit(rule.getUnit().getUnit());
            } else {
            	unit = herb.getDosage();
           }
        }
        return unit;
    }

    public Prescription calculate(Prescription p) {
        if (p != null) {
            Set<Herb> herbs = p.getHerbs();
            Iterator<Herb> it = herbs.iterator();
            while (it.hasNext()) {
                Herb herb = it.next();
                Unit u = calculate(herb);
                herb.setUnit(u);
            }
        }
        return p;
    }
    
    public String toString() {
        return name;
    }

    public int getId() {
        return id;
    }

    public void setId(int id) {
        this.id = id;
    }

    public Conversion convert(Prescription p) {
        Prescription tp = calculate(p);
        Conversion cs = new Conversion();
        cs.setPid(p.getId());
        cs.setViewid(id);
        HashMap<Integer, Unit> herbsUnit = tp.getComposition();
        cs.setHerbsUnit(herbsUnit);
        return cs;
    }

    public void addRule(Herb herb, Rule r) {
        rules.put(herb, r);
        
    }
    
}